//
//  FPSettingController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/21.
//

#import "FPSettingController.h"
#import "FPAuthenticationFooterView.h"
#import "FPMyCustomerController.h"
#import "FPAboutUsController.h"
#import "FPSettleListController.h"
#import "FPCleanAccountController.h"
#import "FPSettingCell.h"
#import "FPProtocolListController.h"
#import "FPPushSettingController.h"
#import "FPForgetPasswordController.h"
#import "FPHelpCenterController.h"

@interface FPSettingController () <UITableViewDelegate , UITableViewDataSource , HJCActionSheetDelegate>

@property (nonatomic,strong) NSArray *titleArr1;
@property (nonatomic,strong) NSArray *imgArr1;

@property (nonatomic,strong) NSArray *titleArr2;
@property (nonatomic,strong) NSArray *imgArr2;

//@property (nonatomic , strong) FPAuthenticationFooterView *footerView;

@end

@implementation FPSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)initUI {
    
    [self setTitle:@"设置" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
    self.group_tableView.delegate = self;
    self.group_tableView.dataSource = self;
    [self.view addSubview:self.group_tableView];
    self.group_tableView.rowHeight = 50.f;
    self.group_tableView.separatorStyle = UITableViewCellSeparatorStyleNone; // 显示单行分隔线
    self.group_tableView.frame = CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - 64.f - UIDevice.safeDistanceBottom - UIDevice.navigationFullHeight - 5.f);
    
//    self.imgArr1 = @[@"icon_setting_cell_v2_1" , @"icon_setting_cell_v2_2" , @"icon_setting_cell_v2_4" , @"icon_setting_cell_v2_5" , @"icon_setting_cell_v2_7"];
//    self.titleArr1 = @[@"我的客服", @"权限管理" , @"用户服务协议" , @"用户隐私保护政策" , @"结清证明"];
    self.imgArr1 = @[@"icon_setting_cell_v2_1" , @"icon_setting_cell_v2_2" , @"icon_setting_cell_v2_4" , @"icon_setting_cell_v2_5"];
    self.titleArr1 = @[@"我的客服", @"权限管理" , @"用户服务协议" , @"用户隐私保护政策"];
    
    self.imgArr2 = @[@"icon_setting_cell_v2_8" , @"icon_setting_cell_v2_9" , @"icon_setting_cell_v2_10" , @"icon_setting_cell_v2_11"];
    self.titleArr2 = @[@"关于众鑫花", @"版本号" , @"清理缓存" , @"注销账户"];
    
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    self.group_tableView.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0.f, SCREEN_HEIGHT - 44.f - UIDevice.safeDistanceBottom - 20.f, SCREEN_WIDTH, 64.f + UIDevice.safeDistanceBottom)];
    temp.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    UIButton *nextButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    
    [nextButton setTitleColor:[UIColor hexColor:@"#F12D2D"] forState:(UIControlStateNormal)];
    [nextButton setTitle:@"退出账号" forState:(UIControlStateNormal)];
    nextButton.backgroundColor = UIColor.whiteColor;
    nextButton.layer.cornerRadius = 8.f;
    nextButton.titleLabel.font = BFONT(14.f);
    nextButton.frame = CGRectMake(16.f, 0.f, SCREEN_WIDTH - 32.f, 44.f);
    
    [self.view addSubview:temp];
    [temp addSubview:nextButton];
    

    [nextButton handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitles:@"退出登录", nil];
        [sheet show];
    }];
}

#pragma mark - 退出登录
- (void)actionSheet:(HJCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    [MBManager showLoading];
    [FPUserModel logoutSuccess:^(NSString * _Nonnull message, NSInteger code) {
        [MBManager hideLoading];
        
        [self logoutSuccess];
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        
        return self.imgArr1.count;
    }
    else {
        
        return self.imgArr2.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPSettingCell *cell;
    
    if (cell == nil) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPSettingCell.class) owner:nil options:nil].lastObject;
    }
    
    if (indexPath.section == 0) {
        
        cell.mainImgView.image = IMG(self.imgArr1[indexPath.row]);
        cell.titleLab.text = self.titleArr1[indexPath.row];
        cell.subTitleLab.hidden = YES;
        
        if (indexPath.row == 0) {
            
            [UIView setCornerForView:cell.backView withRadius:8.f bounds:CGRectMake(0.f, 0.f, SCREEN_WIDTH - 32.f, 50.f) corners:(UIRectCornerTopLeft | UIRectCornerTopRight)];
        }
        else if (indexPath.row == self.imgArr1.count - 1) {
            
            [UIView setCornerForView:cell.backView withRadius:8.f bounds:CGRectMake(0.f, 0.f, SCREEN_WIDTH - 32.f, 50.f) corners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)];
            cell.lineView.hidden = YES;
        }
        
        return cell;
    }
    else {
        
        cell.mainImgView.image = IMG(self.imgArr2[indexPath.row]);
        cell.titleLab.text = self.titleArr2[indexPath.row];
        cell.subTitleLab.hidden = YES;
        
        if (indexPath.row == 0) {
            
            [UIView setCornerForView:cell.backView withRadius:8.f bounds:CGRectMake(0.f, 0.f, SCREEN_WIDTH - 32.f, 50.f) corners:(UIRectCornerTopLeft | UIRectCornerTopRight)];
        }
        else if (indexPath.row == self.imgArr2.count - 1) {
            
            [UIView setCornerForView:cell.backView withRadius:8.f bounds:CGRectMake(0.f, 0.f, SCREEN_WIDTH - 32.f, 50.f) corners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)];
            cell.lineView.hidden = YES;
        }
        
        // 版本
        if (indexPath.row == 1) {
            
            cell.arrowImgView.hidden = YES;
            
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *version = infoDictionary[@"CFBundleShortVersionString"];
            cell.subTitleLab.text = [@"v" stringByAppendingString:version];
            
            cell.subTitleLab.hidden = NO;
        }
        // 缓存
        else if (indexPath.row == 2) {
         
            unsigned long long cacheSize = [self calculateCacheSize];
            NSString *formattedSize = [self formattedCacheSize:cacheSize];
            
            cell.subTitleLab.text = formattedSize;
        }
        
        return cell;
    }
    
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        FPSettleListController *settingVC = [[FPSettleListController alloc] init];
        FPMainWebController *webVC = [[FPMainWebController alloc] init];
        
        switch (indexPath.row) {
                
            case 0: // 我的客服
                [self myCustomer];
                break;
                
            case 1: // 权限管理
                
                // 跳转到当前应用的设置页
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                }
                break;
           
            case 2: // 用户服务协议

                webVC.protocolType = FPProtocolTypeSettingUserProtocol;
                [self.navigationController pushViewController:webVC animated:YES];
                break;
            case 3: // 用户隐私保护政策

                webVC.protocolType = FPProtocolTypeSettingPrivacyProtocol;
                [self.navigationController pushViewController:webVC animated:YES];
                break;

            case 4: // 结清证明
                
                [self.navigationController pushViewController:settingVC animated:YES];
                break;
                
            default:
                break;
        }
    }
    else {
        
        switch (indexPath.row) {
            case 0: // 关于众鑫花
                [self aboutUsAction];
                break;
            case 1: // 版本号
                // ... 无
                break;
            case 2: // 清理缓存
                [self clearCache];
                [self.group_tableView reloadData];
                break;
            case 3: // 注销账户
                [self cleanAccount];
                break;
                
            default:
                break;
        }
    }
}

#pragma mark - 注销
- (void)cleanAccount {
    
    FPCleanAccountController *vc = [[FPCleanAccountController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 去 我的客服
- (void)myCustomer {
    
    FPMyCustomerController *vc = [[FPMyCustomerController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}




#pragma mark - 缓存
- (unsigned long long)calculateCacheSize {
    
    // 获取缓存目录路径
    NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    // 获取文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 获取缓存目录下所有的文件
    NSArray *filePaths = [fileManager subpathsAtPath:cacheDirectory];
    
    unsigned long long totalSize = 0;
    
    // 遍历所有文件，累加它们的大小
    for (NSString *filePath in filePaths) {
        NSString *fullPath = [cacheDirectory stringByAppendingPathComponent:filePath];
        
        // 获取文件属性
        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:fullPath error:nil];
        unsigned long long fileSize = [fileAttributes fileSize];
        
        // 累加文件大小
        totalSize += fileSize;
    }
    
    return totalSize;
}

// 格式化缓存
- (NSString *)formattedCacheSize:(unsigned long long)size {
    float sizeInMB = size / (1024.0 * 1024.0);
    if (sizeInMB < 1) {
        return [NSString stringWithFormat:@"%.2f KB", size / 1024.0];
    } else {
        return [NSString stringWithFormat:@"%.2f MB", sizeInMB];
    }
}

- (void)clearCache {
    // 获取缓存目录路径
    NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    // 获取文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 获取缓存目录下所有的文件
    NSArray *filePaths = [fileManager subpathsAtPath:cacheDirectory];
    
    // 遍历所有文件并删除
    for (NSString *filePath in filePaths) {
        NSString *fullPath = [cacheDirectory stringByAppendingPathComponent:filePath];
        
        NSError *error = nil;
        
        // 删除文件
        if ([fileManager fileExistsAtPath:fullPath]) {
            [fileManager removeItemAtPath:fullPath error:&error];
        }
    }
    
    [self showText:@"清除完成"];
}


#pragma mark - 退出登录数据处理
- (void)logoutSuccess {
    
//    [self showText:@"退出成功"];
    [[FPUserModel sharedUser] loginInvalid];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LogoutNotification object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:UserTokenInvalidNotification object:nil];
    
//    [self performSelector:@selector(backAction) withObject:nil afterDelay:1.5f];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 关于我们
- (void)aboutUsAction {
    
    FPAboutUsController *vc = [[FPAboutUsController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


@end
